package com.jxl_dyw.UI;

import com.jxl_dyw.entity.User;
import com.jxl_dyw.hashMap.MyHashMap;

import javax.swing.*;
import java.awt.*;
import java.io.*;

public class LoginUI extends JFrame {

    private JTextField usernameField;
    private JPasswordField passwordField;

    // 管理员信息文件路径
    static String filePath = "src/main/resources/User.csv";
    //用于存放管理员的哈希表
    private static MyHashMap<String , String> userMap = new MyHashMap<>();
    //get方法
    public static MyHashMap<String, String> getUserMap() {
        return userMap;
    }

    public LoginUI() {

        // 读取文件中的管理员信息
        try {
            readUsersFromFile(filePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 设置窗口标题
        setTitle("员工信息管理系统");

        // 设置窗口大小和关闭操作
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 创建面板并设置布局
        JPanel formPanel = new JPanel();
        //网格布局管理器
        formPanel.setLayout(new GridBagLayout());
        //设置空边框
        formPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST;

        // 添加用户名标签和文本框
        JLabel usernameLabel = new JLabel("账户名:");
        usernameLabel.setFont(new Font("宋体", Font.PLAIN, 20));
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(usernameLabel, gbc);

        usernameField = new JTextField(20);
        gbc.gridx = 1;
        formPanel.add(usernameField, gbc);

        // 添加密码标签和密码框
        JLabel passwordLabel = new JLabel("密码:");
        passwordLabel.setFont(new Font("宋体", Font.PLAIN, 20));
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(passwordLabel, gbc);

        passwordField = new JPasswordField(20);
        gbc.gridx = 1;
        formPanel.add(passwordField, gbc);

        // 添加按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

        // 添加登录按钮
        JButton loginButton = new JButton("登录");
        buttonPanel.add(loginButton);

        // 添加注册按钮
        JButton registerButton = new JButton("注册");
        buttonPanel.add(registerButton);

        // 设置按钮的大小
        loginButton.setPreferredSize(new Dimension(100, 30));
        registerButton.setPreferredSize(new Dimension(100, 30));

        // 将表单面板添加到窗口中央
        add(formPanel, BorderLayout.CENTER);
        // 将按钮面板添加到窗口底部
        add(buttonPanel, BorderLayout.SOUTH);

        // 显示窗口
        setLocationRelativeTo(null); // 窗口居中显示
        setVisible(true);

        //登录按钮的监听事件
        loginButton.addActionListener(e -> {
            // 登录逻辑
            String username = usernameField.getText();
            String password = new String(passwordField.getPassword());

            // 假设验证成功
            if (isValidLogin(username, password)) {
                // 跳转到MainUI
                MainUI mainUI = null;
                try {
                    mainUI = new MainUI();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                mainUI.setVisible(true);
                dispose(); // 关闭当前登录界面
            } else {
                JOptionPane.showMessageDialog(this, "登录失败，请检查用户名和密码。");
            }
        });
        //注册按钮的监听事件
        registerButton.addActionListener(e -> {
            // 跳转到RegisterUI
            RegisterUI registerUI = new RegisterUI();
            registerUI.setVisible(true);
            dispose(); // 关闭当前登录界
        });
    }

    private boolean isValidLogin(String username, String password) {
        // 实现你的登录验证逻辑
        return userMap.get(username) != null && userMap.get(username).equals(password);
    }

    //读取用户表到哈希表
    public void readUsersFromFile(String filePath) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 按逗号分隔每一行
                String[] fields = line.split(",");

                // 创建 User 对象
                User user = new User(fields[0], fields[1]);

                // 将 User 对象添加到哈希表中，以用户名作为键
                userMap.put(user.getUsername(), user.getPassword());
            }
        }
    }

    //将哈希表中的数据写入到CSV文件中
    public static void writeUsersToFile(String filePath) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {

            // 遍历哈希表，将每个用户的信息写入CSV文件
            for (String username : userMap.keys()) {
                writer.write(String.join(",",
                        username,
                        userMap.get(username)
                ));
                writer.newLine();
            }
        }
    }

}
